//
//  FlutterRoute.m
//  hqedu24olapp
//
//  Created by lvfeijun on 2022/9/2.
//  Copyright © 2022 edu24ol. All rights reserved.
//

#import "FlutterRoute.h"

#import <Flutter/Flutter.h>
#import <flutter_boost/FlutterBoost.h>
#import "HqwxEdu_FeedbackVC.h"
#import "MyFlutterBoostDelegate.h"

#import "Login_CustomMananger.h"
#import "SMSCodeManager.h"
#import "LogOutManager.h"

@interface FlutterRoute ()

@property (nonatomic, strong) NSMutableArray *FBVoidCallbackArray;
@property (nonatomic, strong) FlutterViewController *flutterV;

@end

@implementation FlutterRoute

- (NSMutableArray *)FBVoidCallbackArray
{
    if (!_FBVoidCallbackArray) {
        _FBVoidCallbackArray = NSMutableArray.array;
    }
    return _FBVoidCallbackArray;
}

+ (instancetype)shareFlutterRoute
{
    static FlutterRoute *router = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        router = [[FlutterRoute alloc] init];
    });
    return router;
}

+ (void)setUpFlutterWithApplication:(UIApplication *)application navigationController:(UINavigationController *)navigationController
{
    [FlutterRoute shareFlutterRoute];
    MyFlutterBoostDelegate* delegate=[[MyFlutterBoostDelegate alloc ] init];
    [[FlutterBoost instance] setup:application delegate:delegate callback:^(FlutterEngine *engine) {
        DDLogDebug(@"engine:%@",engine);
    } ];
    delegate.navigationController = navigationController;
}

+ (void)goToLogin
{
    [self btn_click:@"login"];
}

+ (void)btn_click:(NSString *)route
{
    ///引擎必须提前初始化,解决（1）（2）问题
    FlutterBoostRouteOptions* options = [[FlutterBoostRouteOptions alloc]init];
    options.pageName = route;
    if ([route isEqualToString:@"route1"]) {
        route = @"login";
    } else if([route isEqualToString:@"route2"]) {
        route = @"register";
    } else if([route isEqualToString:@"splash"]) {
        route = @"smsLogin";
    } else if([route isEqualToString:@"otherPage"]) {
        route = @"resetPassword";
    }
    options.arguments = @{@"present":@(YES),@"animated":@(YES),@"data":@"data"};
    options.pageName = route;
    //页面是否透明（用于透明弹窗场景），若不设置，默认情况下为true
    options.opaque = true;
    //这个是push操作完成的回调，而不是页面关闭的回调！！！！
    options.completion = ^(BOOL completion) {
        DDLogDebug(@"completion:%ld",completion);
    };
    //这个是页面关闭并且返回数据的回调，回调实际需要根据您的Delegate中的popRoute来调用
    options.onPageFinished = ^(NSDictionary *dic) {
        DDLogDebug(@"onPageFinished:%@",dic);
    };

    [[FlutterBoost instance]open:options];
//    [self addCallBackList];
    FBVoidCallback __block loginBlock = [[FlutterBoost instance] addEventListener:^(NSString *name, NSDictionary *arguments) {
        DDLogDebug(@"name:%@ arguments:%@",name,arguments);
        [Login_CustomMananger loginWithPhone:arguments[@"phone"] pwd:arguments[@"psw"] isAuto:NO success:^(Uagent_User *userInfoModel) {
            [SVProgressHUD dismiss];
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:HQPhoneQuickLoginedFlag];
            [Login_CustomMananger saveUserInfo:userInfoModel];
            [[MyFlutterBoostDelegate getCurrentVC] dismissViewControllerAnimated:YES completion:^{
                [MyFlutterBoostDelegate doDeallocFlutterView];
            }];
        } failure:^(NSError *error, Uagent_User *userInfoModel) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showErrorWithStatus:userInfoModel.msginfo.msg?:error.domain];
            });
        }];
    } forName:@"login"];
    
    FBVoidCallback __block smsBlock = [[FlutterBoost instance] addEventListener:^(NSString *name, NSDictionary *arguments) {
        DDLogDebug(@"name:%@ arguments:%@",name,arguments);
        [SVProgressHUD show];
        [SMSCodeManager getSMSCodeWithPhone:arguments[@"phone"] uid:@"0" optStr:@"login" success:^(NSInteger statuCode, NSString *msg) {
            [SVProgressHUD dismiss];
            if (statuCode == 1) {
                [SVProgressHUD showSuccessWithStatus:@"验证码已发送"];
            }
            else {
                [SVProgressHUD showErrorWithStatus:msg];
            }
        } failure:^(NSError *error) {
            [SVProgressHUD showErrorWithStatus:error.domain];
        }];
    } forName:@"sms"];
    
    FBVoidCallback __block smsLoginBlock = [[FlutterBoost instance] addEventListener:^(NSString *name, NSDictionary *arguments) {
        DDLogDebug(@"name:%@ arguments:%@",name,arguments);
        [SVProgressHUD show];
        [Login_CustomMananger loginWithPhone:arguments[@"phone"] smscode:arguments[@"code"] smsReg:1 success:^(Uagent_User *userInfoModel) {
            [SVProgressHUD dismiss];
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:HQPhoneQuickLoginedFlag];
            [Login_CustomMananger saveUserInfo:userInfoModel];
            [[MyFlutterBoostDelegate getCurrentVC] dismissViewControllerAnimated:YES completion:^{
                [MyFlutterBoostDelegate doDeallocFlutterView];
            }];
        } failure:^(NSError *error, Uagent_User *userInfoModel) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showErrorWithStatus:userInfoModel.msginfo.msg?:error.domain];
            });
        }];
    } forName:@"smsLogin"];
    
    FBVoidCallback __block smsResetpswBlock = [[FlutterBoost instance] addEventListener:^(NSString *name, NSDictionary *arguments) {
        DDLogDebug(@"name:%@ arguments:%@",name,arguments);
        [SVProgressHUD show];
        [SMSCodeManager getSMSCodeWithPhone:arguments[@"phone"]  uid:@"0" optStr:@"resetpwd" success:^(NSInteger statuCode, NSString *msg) {
            [SVProgressHUD dismiss];
        } failure:^(NSError *error) {
            [SVProgressHUD showErrorWithStatus:error.domain];
        }];
    } forName:@"smsResetpsw"];
    
    FBVoidCallback __block resetpswBlock = [[FlutterBoost instance] addEventListener:^(NSString *name, NSDictionary *arguments) {
        DDLogDebug(@"name:%@ arguments:%@",name,arguments);
        [SVProgressHUD show];
        [ResetPasswordManager resetPasswordWithPhone:arguments[@"phone"]  uid:@"0" smsCode:arguments[@"code"] pwd:arguments[@"password"] success:^(NSInteger statuCode, NSString *msg) {
            [LogOutManager logoutWithPassport:nil success:nil failure:nil];
            [SVProgressHUD showSuccessWithStatus:@"新密码设置成功"];
        } failure:^(NSError *error) {
            [SVProgressHUD showErrorWithStatus:error.domain];
        }];
    } forName:@"resetpsw"];
    
    [FlutterRoute shareFlutterRoute].FBVoidCallbackArray = @[loginBlock,smsBlock,smsLoginBlock,smsResetpswBlock,resetpswBlock];
//    [[FlutterRoute shareFlutterRoute].FBVoidCallbackArray addObject:callBlock];
    return;
    [self jumpToFlutterBoost:route];
    return;
    [self jumpToFlutter:route];
}

+ (void)addCallBackWithName:(NSString *)name
                      block:(void (^)(NSString *name, NSDictionary *arguments)) block
{
//    NSMutableArray *listArray = [NSMutableArray array];
//    if ([[FlutterRoute shareFlutterRoute].FBVoidCallbackArray isKindOfClass:NSArray.class]) {
//        [listArray addObjectsFromArray:[FlutterRoute shareFlutterRoute].FBVoidCallbackArray];
//    }
    FBVoidCallback callBlock = [[FlutterBoost instance] addEventListener:^(NSString *name, NSDictionary *arguments) {
        DDLogDebug(@"name:%@ arguments:%@",name,arguments);
        if (block) {
            block(name,arguments);
        }
    } forName:name];
    
    [[FlutterRoute shareFlutterRoute].FBVoidCallbackArray addObject:callBlock];
}

+ (void)addCallBackList
{
    [self addCallBackWithName:@"login" block:^(NSString *name, NSDictionary *arguments) {
        [SVProgressHUD show];
        [Login_CustomMananger loginWithPhone:arguments[@"phone"] pwd:arguments[@"psw"] isAuto:NO success:^(Uagent_User *userInfoModel) {
            [SVProgressHUD dismiss];
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:HQPhoneQuickLoginedFlag];
            [Login_CustomMananger saveUserInfo:userInfoModel];
            [[MyFlutterBoostDelegate getCurrentVC] dismissViewControllerAnimated:YES completion:^{
                [MyFlutterBoostDelegate doDeallocFlutterView];
            }];
        } failure:^(NSError *error, Uagent_User *userInfoModel) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showErrorWithStatus:userInfoModel.msginfo.msg?:error.domain];
            });
        }];
    }];
    
    [self addCallBackWithName:@"sms" block:^(NSString *name, NSDictionary *arguments) {
        [SVProgressHUD show];
        [SMSCodeManager getSMSCodeWithPhone:arguments[@"phone"] uid:@"0" optStr:@"login" success:^(NSInteger statuCode, NSString *msg) {
            [SVProgressHUD dismiss];
            if (statuCode == 1) {
                [SVProgressHUD showSuccessWithStatus:@"验证码已发送"];
            }
            else {
                [SVProgressHUD showErrorWithStatus:msg];
            }
        } failure:^(NSError *error) {
            [SVProgressHUD showErrorWithStatus:error.domain];
        }];
    }];
    [self addCallBackWithName:@"smsLogin" block:^(NSString *name, NSDictionary *arguments) {
        [SVProgressHUD show];
        [Login_CustomMananger loginWithPhone:arguments[@"phone"] smscode:arguments[@"code"] smsReg:1 success:^(Uagent_User *userInfoModel) {
            [SVProgressHUD dismiss];
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:HQPhoneQuickLoginedFlag];
            [Login_CustomMananger saveUserInfo:userInfoModel];
            [[MyFlutterBoostDelegate getCurrentVC] dismissViewControllerAnimated:YES completion:^{
                [MyFlutterBoostDelegate doDeallocFlutterView];
            }];
        } failure:^(NSError *error, Uagent_User *userInfoModel) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showErrorWithStatus:userInfoModel.msginfo.msg?:error.domain];
            });
        }];
    }];
    
    [self addCallBackWithName:@"smsResetpsw" block:^(NSString *name, NSDictionary *arguments) {
        [SVProgressHUD show];
        [SMSCodeManager getSMSCodeWithPhone:arguments[@"phone"]  uid:@"0" optStr:@"resetpwd" success:^(NSInteger statuCode, NSString *msg) {
            [SVProgressHUD dismiss];
        } failure:^(NSError *error) {
            [SVProgressHUD showErrorWithStatus:error.domain];
        }];
    }];
    
    [self addCallBackWithName:@"resetpsw" block:^(NSString *name, NSDictionary *arguments) {
        [SVProgressHUD show];
        [ResetPasswordManager resetPasswordWithPhone:arguments[@"phone"]  uid:@"0" smsCode:arguments[@"code"] pwd:arguments[@"password"] success:^(NSInteger statuCode, NSString *msg) {
            [LogOutManager logoutWithPassport:nil success:nil failure:nil];
            [SVProgressHUD showSuccessWithStatus:@"新密码设置成功"];
        } failure:^(NSError *error) {
            [SVProgressHUD showErrorWithStatus:error.domain];
        }];
    }];
    
    
}

+ (NSArray *)getFBVoidCallbackArray
{
    return [FlutterRoute shareFlutterRoute].FBVoidCallbackArray;
}

+ (void)resetFBVoidCallbackArray
{
    [FlutterRoute shareFlutterRoute].FBVoidCallbackArray = @[];
}

+ (void) jumpToFlutter:(NSString *)route
{
    [[HQTabBarRootViewController currentWidowsViewController].navigationController pushViewController:[FlutterRoute shareFlutterRoute].flutterV animated:YES];
    
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    FlutterEngine *flutterEngine = appDelegate.flutterEngine;
    
    NSString *router = @"";
    if ([route isEqualToString:@"splash"]) {
//        router = @"/login";
        router = @"login_page.dart";
        
    } else if([route isEqualToString:@"otherPage"]){
//        router = @"/login/register";
        router = @"register_page.dart";
        
    } else if([route isEqualToString:@"route1"]){
//        router = @"/login/smsLogin";
        router = @"login/page/reset_password_page.dart";
        
    } else if([route isEqualToString:@"route2"]){
//        router = @"/login/resetPassword";
        router = @"sms_login_page.dart";
    }
//    [flutterEngine runWithEntrypoint:nil initialRoute:router];
    [flutterEngine runWithEntrypoint:@"my flutter engine" libraryURI:router];
}

+ (void)jumpToFlutterBoost:(NSString *)route
{
    ///引擎初始化的时候会有引导页？？？
    if ([route isEqualToString:@"splash"]||[route isEqualToString:@"otherPage"]) {
        ///引擎必须提前初始化,解决（1）（2）问题
        FlutterBoostRouteOptions* options = [[FlutterBoostRouteOptions alloc]init];
        options.pageName = route;
        if ([route isEqualToString:@"splash"]) {
            options.arguments = @{@"present":@(YES)};
        } else
        {
            options.arguments = @{@"animated":@(YES)};
        }
       
        //页面是否透明（用于透明弹窗场景），若不设置，默认情况下为true
        options.opaque = true;
        //这个是push操作完成的回调，而不是页面关闭的回调！！！！
        options.completion = ^(BOOL completion) {
            DDLogDebug(@"completion:%ld",completion);
        };
        //这个是页面关闭并且返回数据的回调，回调实际需要根据您的Delegate中的popRoute来调用
        options.onPageFinished = ^(NSDictionary *dic) {
            DDLogDebug(@"onPageFinished:%@",dic);
        };

        [[FlutterBoost instance]open:options];
    } else if([route isEqualToString:@"route1"]){
        //用FlutterBoost没有设置上，只是用了默认的
        /// 引擎不能提前初始化，用push每次都有欢迎页
        FlutterViewController *flutterViewController = [[FlutterViewController alloc]initWithProject:nil initialRoute:@"/route1" nibName:nil bundle:nil];
//        [flutterViewController setInitialRoute:route];
        [[HQTabBarRootViewController currentWidowsViewController].navigationController pushViewController:flutterViewController animated:YES];
    } else if([route isEqualToString:@"route2"]){
        //用FlutterBoost没有设置上，只是用了默认的
        /// 引擎必须提前初始化，用prese每次都会卡一下
        FlutterViewController *flutterViewController = [[FlutterViewController alloc]initWithProject:nil initialRoute:@"/route2" nibName:nil bundle:nil];
//        FlutterViewController *flutterViewController = [[FlutterViewController alloc]init];
//        [flutterViewController setInitialRoute:route];
        //只要是全屏就会有欢迎页
//        flutterViewController.modalPresentationStyle = UIModalPresentationOverFullScreen;
        [[HQTabBarRootViewController currentWidowsViewController] presentViewController:flutterViewController animated:YES completion:nil];
    }
}

- (FlutterViewController *)flutterV
{
    if (!_flutterV) {
        _flutterV = [[FlutterViewController alloc]init];
    }
    return _flutterV;
}


@end
